//添加事件结束
Promise.prototype.finally = function(callback) {
  var Promise = this.constructor;
  return this.then(
    function(value) {
      Promise.resolve(callback()).then(
        function() {
          return value;
        }
      );
    },
    function(reason) {
      Promise.resolve(callback()).then(
        function() {
          throw reason;
        }
      );
    }
  );
}
const request = (url, data = {}, method = 'GET') => {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  if (method === 'GET') {
    var h = {
      'Content-Type': 'application/json'
    };
  } else {
    var h = {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    };
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: h,
      success: function(res) {
        console.log("服务器返回数据：", res.data)
        if (res.statusCode == 200) {
          if (res.data.status == 1) {
            resolve(res.data); //返回成功提示信息
          } else {
            reject(res.data.msg + '：' + res.data.status); //返回错误码
            showmsg(res.data.msg + '：' + res.data.status);
          }
        } else {
          reject('网络错误：' + res.statusCode); //返回错误码
          showmsg('网络错误：' + res.statusCode);
        }
      },
      fail: function(res) {
        reject('网络错误：-1'); //返回错误提示信息
        showmsg('网络错误：-1');
      },
      complete: function(res) {
        wx.hideLoading();
      }
    })
  });
}

var showmsg = function(msg) {
  wx.showModal({
    title: '错误',
    content: msg,
    showCancel: false
  })
}

module.exports = {
  request: request
}


/***
 * 
 * 
    app.http(u, d).then(res => {
 
    }).catch(res => {
         console.log('fail:', res);
    }).finally(() => {
       console.log('finally:', "结束");
    })
 * 
 */